<script setup>
	import { defineProps, ref, watchEffect } from 'vue'
	import * as echarts from 'echarts'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'
	import { storeToRefs } from 'pinia'

	const store = useCustomQueryStore()
	const { queryResult } = storeToRefs(store)

	const props = defineProps({
		dataConnectorId: {
			type: String,
			required: true
		},
		sql: {
			type: String,
			required: true
		},
		params: {
			type: Array,
			default: () => []
		}
	})

	// 图表类型选项
	const chartTypes = [
		{ label: '饼图', value: 'pie' },
		{ label: '折线图', value: 'line' },
		{ label: '柱状图', value: 'bar' }
	]

	// 当前选中的图表类型
	const selectedChartType = ref('pie')

	// 图表配置选项
	const chartOptions = ref({
		xField: '',
		yField: '',
		seriesField: ''
	})

	// 可选的字段列表
	const availableFields = ref([])

	// 图表实例
	const chartInstance = ref(null)
	const chartContainer = ref(null)

	// 初始化图表
	const initChart = () => {
		if (chartContainer.value) {
			chartInstance.value = echarts.init(chartContainer.value)
		}
	}

	// 更新可选字段列表
	watchEffect(() => {
		if (queryResult.value && queryResult.value.length > 0) {
			availableFields.value = Object.keys(queryResult.value[0])
			// 默认选择第一个字段作为x轴，第二个字段作为y轴
			if (availableFields.value.length >= 2) {
				chartOptions.value.xField = availableFields.value[0]
				chartOptions.value.yField = availableFields.value[1]
				if (availableFields.value.length >= 3) {
					chartOptions.value.seriesField = availableFields.value[2]
				}
			}
		}
	})

	// 生成图表配置
	const generateChartOption = () => {
		if (!queryResult.value || queryResult.value.length === 0) return null

		const { xField, yField, seriesField } = chartOptions.value
		const data = queryResult.value

		switch (selectedChartType.value) {
			case 'pie':
				return {
					title: {
						text: '饼图示例',
						left: 'center'
					},
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b}: {c} ({d}%)'
					},
					legend: {
						orient: 'vertical',
						left: 'left',
						top: '10%'
					},
					series: [
						{
							name: '数据分布',
							type: 'pie',
							radius: ['0%', '70%'],
							center: ['50%', '55%'],
							data: data.map((item) => ({
								name: item[xField],
								value: item[yField]
							}))
						}
					]
				}

			case 'line':
				return {
					title: {
						text: '折线图示例',
						left: 'center'
					},
					tooltip: {
						trigger: 'axis'
					},
					legend: {
						top: '10%'
					},
					xAxis: {
						type: 'category',
						data: [...new Set(data.map((item) => item[xField]))]
					},
					yAxis: {
						type: 'value'
					},
					series: seriesField
						? [...new Set(data.map((item) => item[seriesField]))].map((series) => ({
								name: series,
								type: 'line',
								data: data.filter((item) => item[seriesField] === series).map((item) => item[yField])
							}))
						: [
								{
									type: 'line',
									data: data.map((item) => item[yField])
								}
							]
				}

			case 'bar':
				return {
					title: {
						text: '柱状图示例',
						left: 'center'
					},
					tooltip: {
						trigger: 'axis'
					},
					legend: {
						top: '10%'
					},
					xAxis: {
						type: 'category',
						data: [...new Set(data.map((item) => item[xField]))]
					},
					yAxis: {
						type: 'value'
					},
					series: seriesField
						? [...new Set(data.map((item) => item[seriesField]))].map((series) => ({
								name: series,
								type: 'bar',
								data: data.filter((item) => item[seriesField] === series).map((item) => item[yField])
							}))
						: [
								{
									type: 'bar',
									data: data.map((item) => item[yField])
								}
							]
				}

			default:
				return null
		}
	}

	// 更新图表
	const updateChart = () => {
		if (!chartInstance.value) return

		const option = generateChartOption()
		if (option) {
			chartInstance.value.setOption(option, true)
			// 强制重新计算图表大小
			chartInstance.value.resize()
		}
	}

	watchEffect(() => {
		if (selectedChartType.value) {
			updateChart()
		}
	})

	// 组件挂载时初始化图表
	onMounted(() => {
		// initChart()
	})

	// 组件卸载时销毁图表
	onUnmounted(() => {
		if (chartInstance.value) {
			chartInstance.value.dispose()
		}
	})
</script>
<template>
	<div class="chart-preview">
		<div class="chart-controls">
			<a-space>
				<a-select v-model:value="selectedChartType" style="width: 120px" placeholder="选择图表类型">
					<a-select-option v-for="type in chartTypes" :key="type.value" :value="type.value">
						{{ type.label }}
					</a-select-option>
				</a-select>
				<div v-if="queryResult && queryResult.length > 0">
					<a-space>
						<a-select v-model:value="chartOptions.xField" style="width: 120px" placeholder="选择X轴字段">
							<a-select-option v-for="field in availableFields" :key="field" :value="field">
								{{ field }}
							</a-select-option>
						</a-select>

						<a-select v-model:value="chartOptions.yField" style="width: 120px" placeholder="选择Y轴字段">
							<a-select-option v-for="field in availableFields" :key="field" :value="field">
								{{ field }}
							</a-select-option>
						</a-select>

						<a-select v-model:value="chartOptions.seriesField" style="width: 120px" placeholder="选择系列字段（可选）">
							<a-select-option v-for="field in availableFields" :key="field" :value="field">
								{{ field }}
							</a-select-option>
						</a-select>
					</a-space>
				</div>
			</a-space>
		</div>

		<div ref="chartContainer" class="chart-container"></div>
	</div>
</template>

<style scoped>
	.chart-preview {
		padding: 16px;
		position: relative;
		z-index: 1000;
	}

	.chart-controls {
		margin-bottom: 16px;
		position: relative;
		z-index: 1001;
	}

	.chart-container {
		width: 100%;
		height: 400px;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		position: relative;
		z-index: 1000;
		overflow: visible;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
